package lspCliente;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;

import lspUtils.*;


public class LspClient   {
	
	private DatagramSocket socket;
	private LspParams lspParams;
	
	public LspClient(String serverHost, int port, LspParams lspParams) throws IOException {
		//super(InetAddress.getByName(serverHost), 5000, lspParams);
		this.lspParams = lspParams;
		this.socket = new DatagramSocket(port);
		
		//startServices();
		connectToServer();
	}
	
	/**
	 * @param serverHost
	 * @param port
	 * @param lspParams2
	 */
	
	public void connectToServer() throws SocketException {
		LspPacket lspPacket = new LspPacket(MessageType.CONNECT, (short) 0, (short) 0);
		sendPacket(lspPacket);
		
		waitAckConnect();
	}
	
	private void waitAckConnect() throws SocketException {
		long t0 = System.currentTimeMillis();
		while (!isConnected()) {
			if (System.currentTimeMillis() - t0 > lspParams.getEpoch()) {
				throw new SocketException("Erro ao tentar conectar");
			}
		}
	}

	
	public short getConnId() {
		return getConnectionId();
	}

	
	public byte[] read() {
		LspPack pack = null;
		while (pack == null) {
			pack = popReceivedExternalPack();
		}
		return pack.getPayload();
	}

	
	public void write(byte[] payload) {
		if (payload.length > 1000) {
			throw new IllegalArgumentException("O tamanho da mensagem deve ser menor que 1000 bytes.");
		}
		LspPack pack = new LspPack(getConnectionId(), payload);
		lspSender.sendData(pack);
	}
	
	
	public LspPacket popReceivedLspPacket()  {
		byte[] buf = new byte[1000];
		DatagramPacket packet = new DatagramPacket(buf, buf.length);
		try {
			socket.receive(packet);
			return LspPacket.fromDatagramPacket(packet);
		} catch (SocketException e) {
			// socket closed: terminate execution
		} catch (IOException e) {
			e.printStackTrace();
		}
		return null;
	}
	
	
	public void close() {
		setConnectionId((short) 0);
		socket.close();
		super.close();
	}

}
